<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Request;
//use App\Helpers;

class User extends Model
{
    // 注册 api
    public function signup()
    {
        $has_username_and_password = $this->has_username_and_password();
        // 检查用户名和密码是否为空
        if (!$has_username_and_password) {
            return ['status' => 0, 'msg' => '用户名和密码皆不可为空'];
        }
        $username = $has_username_and_password[0];
        $password = $has_username_and_password[1];

        // 检查用户名是否存在
        $user_exists = $this
            ->where('username', $username)
            ->exists();

        if ($user_exists) {
            return ['status' => 0, 'msg' => '用户名已存在'];
        }

        // 加密密码
        $hashed_password = bcrypt($password);

        // 存入数据库
        $user = $this;
        $user->password = $hashed_password;
        $user->username = $username;
        if ($user->save()) {
            return ['status' => 1, 'id' => $user->id];
        } else {
            return ['status' => 0, 'msg' => 'db insert failed'];
        }
    }

    // 获取用户信息 api
    public function read()
    {
        if (!rq('id')) {
            return err('required id');
        }

        $get = ['id', 'username', 'avatar_url', 'intro'];
        $user = $this->find(rq('id'), $get);
        $data = $user->toArray();
        $answer_count = answer_ins()->where('user_id', rq('id'))->count();
        $question_count = question_ins()->where('user_id', rq('id'))->count();
 //        $answer_count = $user->answers()->count();
//        $question_count = $user->questions()->count();
        $data['answer_count'] = $answer_count;
        $data['question_count'] = $question_count;

        return suc($data);

    }

    // 登录 api
    public function login()
    {
        // 检查用户名和密码是否存在
        $has_username_and_password = $this->has_username_and_password();
        if (!$has_username_and_password) {
            //return ['status' => 0, 'msg' => 'username and password are required'];
            return err('username and password are required');
        }

        $username = $has_username_and_password[0];
        $password = $has_username_and_password[1];
        // 在数据库查找是否有该用户（检查用户是否存在）
        $user = $this->where('username', $username)->first();
        if (!$user) {
            // return ['status' => 0, 'msg' => 'user not exists'];
            return err('user not exists');
         }

         // 检查密码是否正确
        $hashed_password = $user->password;
        if (!Hash::check($password, $hashed_password)) {
            //return ['status' => 0, 'msg' => 'invalid password'];
            return err('invalid password');
        }

        // 将用户信息写入 session
        session()->put('username', $user->username);
        session()->put('user_id', $user->id);

        //return ['status' => 1, 'id' => $user->id];
        return suc(['id' => $user->id]);
    }

    public function has_username_and_password()
    {
        $username = rq('username');
        $password = rq('password');
        if ($username && $password) {
            return [$username, $password];
        } else {
            return false;
        }
    }

    // 登出 api
    public function logout()
    {
        //session()->flush();
        //session()->put('username', null);
        //session()->put('user_id', null);
        // 删除username  user_id
        session()->forget('username');
        session()->forget('user_id');
        return ['status' => 1];
    }

    // 检测用户是否登录
    public function is_logged_in()
    {
        // 如果session中存在 user_id, 就返回 user_id, 否则返回 false
        return session('user_id') ? : false;
    }

    // 修改密码 api
    public function change_password()
    {
        if (!$this->is_logged_in()) {
            //return ['status' => 1, 'msg' => 'login required'];
            return err('login required');
        }

        if (!rq('old_password')) {
            return ['status' => 0, 'msg' => 'new_password is required'];
        }

        $user = $this->find(session('user_id'));

        if (!Hash::check(rq('old_passwored'), $user->password)) {
            return ['status' => 0, 'msg' => 'invalid old_password'];
        }

        $user->password = bcrypt(rq('new_password'));

        return $user->save() ?
            ['status' => 1] :
            ['status' => 0, 'msg' => 'db update failed'];
    }

    // 找回密码 api
    public function rest_password()
    {
        if ($this->is_robot()) {
            return err('max frequency reached');
        }

        if (!rq('phone')) {
            return err('phone is requried');
        }

        $user = $this->where('phone', rq('phone'))->first();

        if (!$user) {
            return err('invalid phone number');
        }

        // 生成验证码
        $captcha = $this->generate_captcha();

        $user->phone_captcha = $captcha;
        if ($user->save()) {
            // 如果验证码保存成功， 发送验证码短信
            $this->send_sms();
            // 为下一次机器人调用检查做准备
            $this->update_robot_time();
            return suc();
        } else {
            return err('db update failed');
        }
    }

    // 验证找回密码 api
    public function validate_reset_password()
    {
        if ($this->is_robot(2)) {
            return err('max frequency reached');
        }

        if (!rq('phone') || !rq('phone_captcha') || !rq('new_password')) {
            return err('phone, new_password and phonecaptcha are required');
        }
        // 检查用户是否存在
        $user = $this->where([
            'phone' => rq('phone'),
            'phone_captcha' => rq('phone_captcha')
        ])->first();

        if (!$user) {
            return err('invalid phone or invalid phone');
        }
        // 加密新密码
        $user->password = bcrypt(rq('new_password'));
        $this->update_robot_time();

        return $user->save() ?
            suc() : err('db update failed');
    }

    // 检查机器人
    public function is_robot($time = 10)
    {
        // 如果 session中没有 last_sms_time说明接口从未被 调用过
        if (!session('last_sms_time')) {
            return false;
        }
        $current_time = time();
        $last_active_time = session('last_active_time');

        $elapsed = $current_time - $last_active_time;

        return !($elapsed > $time);
    }

    // 更新机器人的行为时间
    public function update_robot_time()
    {
        session(['last_active_time'=>time()]);
    }

    public function send_sms()
    {
        
    }

    // 生成验证码
    public function generate_captcha()
    {
        return rand(1000, 9999);
    }

    public function answers()
    {
        return $this
            ->belongsToMany('App\Answer')
            ->withPivot('vote')
            ->withTimestamps();
    }

    public function questions()
    {
        return $this
            ->belongsToMany('App\Question')
            ->withPivot('vote')
            ->withTimestamps();
    }
}
